//
//  FPDetailCinemaTableViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/15.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPDetailCinemaTableViewController.h"
#import "FPDetailCinemaTableViewCell.h"
#import "FPCinemaTableViewCell.h"
#import "FPCinemaViewController.h"
#import "InfiniteScrollPicker.h"
#import "FPCinemaCollectionViewCell.h"
#import "FPCinemaModel.h"
#import "FPMovieHotPlayModel.h"
#import "iCarousel.h"
#import "FPPlayDetailModel.h"
#import "UIImage+WebP.h"
#define kDCinemaUrl @"http://api.m.mtime.cn/Showtime/ShowtimeMovieAndDateListByCinema.api?cinemaId="
#define kPlayMessageUrl @"http://api.m.mtime.cn/Showtime/ShowTimesByCinemaMovieDate.api?cinemaId=%@&date=%@&movieId=%ld"

@interface FPDetailCinemaTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,iCarouselDataSource,iCarouselDelegate>

{
    InfiniteScrollPicker *_topImage;
    BOOL _isClick;
}
@property (nonatomic, strong) iCarousel *carousel;

@property (nonatomic, strong) UILabel *topLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *typeLabel;
@property (nonatomic, strong) NSMutableArray *set;
@property (nonatomic, strong) NSMutableDictionary *imageDic;
@property (nonatomic, assign) NSInteger imageindex;

// 存放解析出来的model
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSMutableArray *cinemaArray;
@property (nonatomic, strong) NSMutableArray *featureArray;
@property (nonatomic, strong) NSMutableArray *moviesArray;

@property (nonatomic, strong) NSMutableArray * filmArry;
@property (nonatomic, strong) NSMutableArray * playDetailArray;
// 解析影片播放厅信息
@property (nonatomic, copy)   NSString *datakUrl;
@property (nonatomic, assign) NSInteger movieIdkUrl;
@property (nonatomic) NSInteger lblIndex;

@end

@implementation FPDetailCinemaTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 左上角返回barbutton
//   [self B_backBarButton];
    
    // 右上角barbutton
    [self B_rightBarButton];
    
    // 解析数据
    [self T_analisisDetailCinema];
    [self S_analisisPlayMessage];

}

/*==============================================解析数据=================================================*/
#pragma mark - 解析网络数据
- (void)T_analisisDetailCinema
{
    
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kDCinemaUrl,_kUrl]]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    
    //开启异步连接
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               if (data == nil) return;
                               NSDictionary *detailDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                               // 初始化数组
                               self.cinemaArray  = [NSMutableArray array];
                               self.featureArray = [NSMutableArray array];
                               self.moviesArray  = [NSMutableArray array];
                               self.titleArray   = [NSMutableArray array];
                               self.set          = [NSMutableArray array];
                               
                               NSDictionary *cinemaDic = [detailDic objectForKey:@"cinema"];
                               FPCinemaModel *model = [FPCinemaModel cinemaModelWithDictionary:cinemaDic];
                               [self.cinemaArray addObject:model];
                               
                               NSDictionary *featureDic = [cinemaDic objectForKey:@"feature"];
                               FPCinemaModel *featureModel = [FPCinemaModel cinemaModelWithDictionary:featureDic];
                               [self.featureArray addObject:featureModel];
                               
                               NSArray *array = [detailDic objectForKey:@"movies"];
                               [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
                                   FPMovieHotPlayModel *model = [FPMovieHotPlayModel MovieHotPlayWithDictionary:dic];
                                   [self.moviesArray addObject:model];
                                   self.titleArray = [dic objectForKey:@"showDates"];
                                   NSString *str = [dic objectForKey:@"img"];
                                   [self.set addObject:str];
                               }];
                               
                               [self.tableView reloadData];
                           }];
    
}

- (void)S_analisisPlayMessage
{
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:kPlayMessageUrl,_kUrl,_datakUrl,_movieIdkUrl]]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:20.0];
    // 开启异步请求
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                           if (data == nil) return;
                                           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                           // 初始化数组
                                           self.filmArry        = [NSMutableArray array];
                                           self.playDetailArray = [NSMutableArray array];
                                           
                                           FPPlayDetailModel *model = [FPPlayDetailModel PlayDetailWithDictionary:dic];
                                           [self.filmArry addObject:model];
                                           NSArray *array = [dic objectForKey:@"s"];
                                           [array enumerateObjectsUsingBlock:^(NSDictionary *sDic, NSUInteger idx, BOOL *stop) {
                                               FPPlayDetailModel *sModel = [FPPlayDetailModel PlayDetailWithDictionary:sDic];
                                               [self.playDetailArray addObject:sModel];
                                           }];
                                           [self.tableView reloadData];
                                       }];
}


/*==============================================搭建视图=================================================*/
#pragma mark - 搭建视图
// 左上角返回barbutton
- (void)B_backBarButton
{
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-vector"]  style:UIBarButtonItemStyleDone target:self action:@selector(backButtonAction:)];
    self.navigationItem.leftBarButtonItem = backButton;
}

// 右上角按键
- (void)B_rightBarButton
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth - 90, 0, 75, 30)];
    
    UIButton *collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    collectBtn.frame = CGRectMake(0, 0, 30, 30);
    [collectBtn setBackgroundImage:[UIImage imageNamed:@"like-vector"] forState:UIControlStateNormal];
    [collectBtn setBackgroundImage:[UIImage imageNamed:@"box-vector"] forState:UIControlStateSelected];
    [collectBtn addTarget:self action:@selector(collectionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:collectBtn];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(35, 0, 40, 30);
    [shareBtn setBackgroundImage:[UIImage imageNamed:@"thumb-up-vector"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:shareBtn];
    
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = rightBtn;
}

/*==============================================方法实现=================================================*/
#pragma mark - 方法实现
// 是否收藏
- (void)collectionBtnAction:(UIButton *)button
{
    NSLog(@"是否收藏");
}

// 是否分享
- (void)shareBtnAction:(UIBarButtonItem *)button
{
    NSLog(@"是否分享");
}

// 左上角返回barbutton实现方法
- (void)backButtonAction:(UIBarButtonItem *)button
{
    NSLog(@"返回到上一页");
    //[self dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"%@",[self.navigationController class]);
//    FPCinemaViewController *fpc = [[FPCinemaViewController alloc]init];
//    [self.navigationController popToViewController:fpc animated:YES];
    [self.navigationController popViewControllerAnimated:NO];
}

/*==============================================tableView协议方法=================================================*/
#pragma mark - Table view 方法
// 每行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kImageH(90);
}

// 有多少分组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

// 每个分组有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return _playDetailArray.count;
    }
}

// 设置表尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 160;
    }else{
        return 0;
    }
}

// 设置表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else{
    return 30;
    }
}

#pragma mark - 设置headerView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//    UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
//    myView.backgroundColor = [UIColor colorWithWhite:0.906 alpha:1.000];
//    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 150, 30)];
//    label.font = [UIFont systemFontOfSize:19.0 weight:2.0];
//    label.text = @"今天(7月15日)";
//    [myView addSubview:label];
    
//    self.titleArray = @[@"今天(7月15日)",@"明天(7月16日)",@"后天(7月17日)"];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30) collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.backgroundColor = [UIColor whiteColor];
    
    return collectionView;
}


#pragma mark - 设置表尾视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    FPMovieHotPlayModel *model = [[FPMovieHotPlayModel alloc] init];
    model = _moviesArray[0];
    
    UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageH(160))];
//    view.backgroundColor = [UIColor grayColor];
    view = [self lurImageView];
    view.userInteractionEnabled = YES;
    
    self.carousel = [[iCarousel alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 100)];
   self.carousel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.carousel.type = iCarouselTypeRotary;
    self.carousel.delegate = self;
    self.carousel.dataSource = self;
    [view addSubview:_carousel];
    
    self.topLabel = [[UILabel alloc] initWithFrame:CGRectMake(kImageW(kScreenWidth / 2 -80), kImageH(105), kImageW(160) , kImageH(30))];
    self.topLabel.textColor = [UIColor whiteColor];
    self.topLabel.text = model.title;
    self.topLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:_topLabel];
    
    self.timeLabel = [UILabel labelWithFrame:CGRectMake(kImageW(kScreenWidth / 2 -80), kImageH(135), kImageW(75), kImageH(10)) text:[NSString stringWithFormat:@"%ld分钟",model.length] color:[UIColor whiteColor]];
    self.timeLabel.font = [UIFont systemFontOfSize:14.0];
    [view addSubview:_timeLabel];
    
    UILabel * sepLabel = [UILabel labelWithFrame:CGRectMake(kImageW(kScreenWidth / 2 -18), kImageH(137), kImageW(10), kImageH(10)) text:@"一" color:[UIColor whiteColor]];
    [view addSubview:sepLabel];
    
    self.typeLabel = [UILabel labelWithFrame:CGRectMake(kScreenWidth / 2 , kImageH(135), kImageW(120), kImageH(10)) text:model.type color:[UIColor whiteColor]];
    self.typeLabel.font = [UIFont systemFontOfSize:14.0];
    [view addSubview:_typeLabel];
    
    return view;
}

// 设置模糊背景
- (UIImageView *)lurImageView
{
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageH(160))];
    backImage.image = [UIImage imageNamed:@"step.jpg"];
    backImage.userInteractionEnabled = YES;
    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    visualEffectView.frame = backImage.bounds;
    visualEffectView.alpha = 0.7;
    [backImage addSubview:visualEffectView];
    return backImage;
    
}
#pragma mark - iCarousel methods
- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return _moviesArray.count;
}

- (UIView *) carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
    view = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 150, 100)];
    [((UIImageView *)view) sd_setImageWithURL:_set[index] placeholderImage:[UIImage imageNamed:@"2.jpg"] completed:nil];
    
    return view;
}

- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
   
    FPMovieHotPlayModel *model = [[FPMovieHotPlayModel alloc] init];
    model = _moviesArray[index];
    self.topLabel.text  = model.title;
    self.timeLabel.text = [NSString stringWithFormat:@"%ld分钟 ",model.length];
    self.typeLabel.text = model.type;
    
}
- (void)carouselCurrentItemIndexDidChange:(iCarousel *)carousel
{
   
    FPMovieHotPlayModel *model = [[FPMovieHotPlayModel alloc] init];
    model = _moviesArray[carousel.currentItemIndex];
    self.topLabel.text  = model.title;
    self.timeLabel.text = [NSString stringWithFormat:@"%ld分钟 ",model.length];
    self.typeLabel.text = model.type;
}

#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *cellIdentifier = @"cell1";
        [tableView registerClass:[FPCinema_TableViewCell class] forCellReuseIdentifier:cellIdentifier];
        FPCinema_TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        FPCinemaModel *model = [[FPCinemaModel alloc] init];
        model = self.cinemaArray[0];
        FPCinemaModel *feature = [[FPCinemaModel alloc] init];
        feature = self.featureArray[0];
        
        cell.cinemaNameLabel.text   = model.name;
        cell.addressLabel.text      = model.address;
        feature.hasPark ? (cell.parkImageView.hidden = NO) : (cell.parkImageView.hidden = YES);
        feature.hasWifi ? (cell.wifiImageView.hidden = NO) : (cell.wifiImageView.hidden = YES);
        feature.has3D ? (cell.thirdDImageView.hidden = NO) : (cell.thirdDImageView.hidden = YES);
        feature.hasServiceTicket ? (cell.ATSImageView.hidden = NO) : (cell.ATSImageView.hidden = YES);
        feature.hasVIP ? (cell.vipImageView.hidden = NO) : (cell.vipImageView.hidden = YES);
        cell.nextImageView.image = [UIImage imageNamed:@"forward-vector"];
        cell.upLabel.text = nil;
        cell.priceLabel.text = nil;
        cell.moneyLabel.text = nil;
        return cell;
    }else{
        static NSString *cellIdentifier = @"cell2";
        [tableView registerClass:[FPDetailCinemaTableViewCell class] forCellReuseIdentifier:cellIdentifier];
        FPDetailCinemaTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        
        FPPlayDetailModel *model = self.playDetailArray[indexPath.row];
        [cell.DetailButton addTarget:self action:@selector(DetailButton:) forControlEvents:UIControlEventTouchUpInside];
        cell.playTypeLabel.text  = [NSString stringWithFormat:@"%@/%@",model.versionDesc,model.language];
        cell.playAddrLabel.text  = model.hall;
        cell.priceLabel.text     = [NSString stringWithFormat:@"%ld",model.price];
        
        NSInteger startTime = [model.showDay integerValue];
        NSInteger endTime   = [model.showDay integerValue] + model.length*60;
        NSDate *startDate   = [NSDate dateWithTimeIntervalSince1970:startTime];
        NSDate *endDate     = [NSDate dateWithTimeIntervalSince1970:endTime];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"HH:mm"];
        NSString *startDateString = [dateFormat stringFromDate:startDate];
        NSString *endDateString   = [dateFormat stringFromDate:endDate];
        cell.startTimeLabel.text  = startDateString;
        cell.endTimeLabel.text    = endDateString;
        
        
        /* 本页面所有控件
         UIButton *DetailButton;  // 点击查看详情
         UILabel *startTimeLabel; // 影院影片开播时间
         UILabel *endTimeLabel;   // 影院影片播止时间
         UILabel *playTypeLabel;  // 播放影片类型
         UILabel *playAddrLabel;  // 播放影片厅所在位置
         UILabel *moneySymbelLabel;// 价格符号
         UILabel *priceLabel;     // 价格
         */
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

- (void)DetailButton:(UIButton *)button
{
    NSLog(@"点击查看影片详情");
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

/*==============================================collectionView协议方法=================================================*/
#pragma mark - collectionView协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _titleArray.count;
}
#pragma mark - 返回cell
// 返回collectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"collectionCell";
    [collectionView registerClass:[FPCinemaCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    FPCinemaCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    cell.label.text = self.titleArray[indexPath.item];
    
    
    
    
    if (_isClick == YES) {
        (indexPath.item == _lblIndex) ? (cell.label.textColor = [UIColor orangeColor]) : (cell.label.textColor = [UIColor lightGrayColor]);
    }else{
         (indexPath.item == 0) ? (cell.label.textColor = [UIColor orangeColor]) : (cell.label.textColor = [UIColor lightGrayColor]);
    }
    
    return cell;
}

// collection点击cell方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    for (FPCinemaCollectionViewCell *cell in collectionView.visibleCells) {
        cell.label.textColor = [UIColor lightGrayColor];
    }
    self.lblIndex = indexPath.row;
    NSLog(@"///%ld",indexPath.item);
    _isClick = YES;
    FPCinemaCollectionViewCell *cell = (FPCinemaCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label.textColor = [UIColor orangeColor];
    // 传值
    FPMovieHotPlayModel *model = [[FPMovieHotPlayModel alloc] init];
    model = _moviesArray[indexPath.item];
    self.movieIdkUrl = model.movieId;
    self.datakUrl = _titleArray[indexPath.item];
    [self S_analisisPlayMessage];
}

//----返回cell宽和高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kScreenWidth / 3, 30);
}



@end
